package net.huashitong.zhApp.controller;

import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.NumberUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.oversee.entity.GradePoint;
import net.huashitong.oversee.entity.ScoreSummary;
import net.huashitong.oversee.filter.GradePointFilter;
import net.huashitong.oversee.filter.ScoreSummaryFilter;
import net.huashitong.oversee.service.GradePointService;
import net.huashitong.oversee.service.ScoreSummaryService;
import net.huashitong.taskGroup.entity.JobGroup;
import net.huashitong.taskGroup.service.JobGroupService;
import net.huashitong.user.entity.BnpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigInteger;
import java.util.*;

@Controller
@RequestMapping(value = "/zhApp/gradepoint")
public class AppGradepointController extends BaseCtrl {

    @Autowired
    private JobGroupService jobGroupService;
    @Autowired
    private GradePointService gradePointService;
    @Autowired
    private ScoreSummaryService scoreSummaryService;


    @ResponseBody
    @RequestMapping(value = "/lists", method = RequestMethod.POST)
    public Map<String, Object> gradePointList(@RequestBody GradePointFilter filter) {

        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            return coverMessage("202", "无用户权限");
        } else {
            //***********************用户情况***********************
            String branchType = user.getBranchType();
            String checkObjectId = user.getSysId();
            String phone = user.getPhone();

            List<JobGroup> jobGroups = jobGroupService.query();
            Map<String, String> jobGroupMap = new HashMap<>();
            for (JobGroup j : jobGroups) {
                if (!jobGroupMap.containsKey(j.getGroupTel())) {
                    jobGroupMap.put(j.getGroupTel(), j.getGroupCode());
                }
            }

            //非（管理员、督查组、领导）
            if (!"2".equals(branchType) && !"4".equals(branchType) && !"6".equals(branchType)) {
                filter.setCheckObjectId(checkObjectId);
            }
            //督查组
            if ("4".equals(branchType)) {
                if (StringUtils.isNotBlank(jobGroupMap.get(phone))) {
                    filter.setCheckObjectId(jobGroupMap.get(phone));
                }
            }

            if (StringUtils.isNotBlank(filter.getCheckType())) {
                if (filter.getPaging().getCurrentPage() == 1) {
                    List<GradePoint> allList = gradePointService.queryGradePointByCheckType(filter.getCheckType());
                    Collections.sort(allList, new Comparator<GradePoint>() {
                        @Override
                        public int compare(GradePoint g1, GradePoint g2) {
                            double score1 = Double.parseDouble(StringUtils.isBlank(g1.getSoucre()) ? "0" : g1.getSoucre());
                            double score2 = Double.parseDouble(StringUtils.isBlank(g2.getSoucre()) ? "0" : g2.getSoucre());
                            if (score1 < score2) {
                                return 1;
                            } else if (score1 == score2) {
                                return 0;
                            } else {
                                return -1;
                            }
                        }
                    });
                    for (int i = 0, s = allList.size(); i < s; i++) {
                        if (i > 0 && Double.parseDouble(StringUtils.isBlank(allList.get(i).getSoucre()) ? "0" : allList.get(i).getSoucre())
                                == Double.parseDouble(StringUtils.isBlank(allList.get(i - 1).getSoucre()) ? "0" : allList.get(i - 1).getSoucre())) {
                            allList.get(i).setTypeRank(allList.get(i - 1).getTypeRank());
                        } else {
                            allList.get(i).setTypeRank(i + 1 + "");
                        }
                    }
                    gradePointService.batchUpdate(allList);
                }
                List<GradePoint> lists = gradePointService.queryGradePoint(filter);
                for (GradePoint gradePoint : lists) {
                    gradePoint.setRank(gradePoint.getTypeRank());
                }
                Map<String, Object> result = new HashMap<>();
                result.put("code", "200");
                result.put("message", "成功获取数据");
                result.put("userAuth", user);
                result.put("data", lists);
                result.put("count", filter.getPaging().getRecords());
                return result;
            }
            //==========================================================================================================
            List<GradePoint> lists = gradePointService.queryGradePoint(filter);
            Map<String, Object> result = new HashMap<>();
            result.put("code", "200");
            result.put("message", "成功获取数据");
            result.put("userAuth", user);
            result.put("data", lists);
            result.put("count", filter.getPaging().getRecords());
            return result;
        }
    }


    @ResponseBody
    @RequestMapping(value = "/queryGradePointDetailById", method = RequestMethod.POST)
    public Message queryGradePointDetailById(@RequestBody GradePointFilter filter) {
        GradePoint gradePoint = gradePointService.getById(filter.getSysId());
        Message message = new Message();
        message.setCode("200");
        message.setMessage("成功获取日志");
        message.setData(gradePoint);
        return message;
    }

    /**
     * 得分统计
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryScoreStatistics", method = RequestMethod.POST)
    public Map<String, Object> queryScoreStatistics(@RequestBody GradePointFilter filter) {
        /**************************************最新绩效得分**************************************/
        Map<String, Object> result = new HashMap<>();
        BnpUser user = queryUserAuth(filter.getUserPhone());
        if (ObjectUtils.isBlank(user)) {
            return coverMessage("202", "无用户权限");
        }
        Map<String, String> resultMap1 = new HashMap<>();
        List<JobGroup> jobGroups = jobGroupService.query();
        Map<String, String> jobGroupMap = new HashMap<>();
        for (JobGroup j : jobGroups) {
            if (!jobGroupMap.containsKey(j.getGroupTel())) {
                jobGroupMap.put(j.getGroupTel(), j.getGroupCode());
            }
        }
        String checkObjectId = "";
        String branchType = "——";
        if (!"2".equals(user.getBranchType()) && !"4".equals(user.getBranchType())) {
            checkObjectId = user.getSysId();
            if ("1".equals(user.getBranchType())) {
                branchType = "审批部门";
            }
            if ("0".equals(user.getBranchType())) {
                branchType = "业主单位";
            }
        }
        //督查组
        if ("4".equals(user.getBranchType())) {
            if (StringUtils.isNotBlank(jobGroupMap.get(user.getPhone()))) {
                checkObjectId = jobGroupMap.get(user.getPhone());
            }
            branchType = "督查组";
        }
        //单独出来的一个汇总信息
        //非督查组
//        DecimalFormat df = new DecimalFormat("#.00");
        if (!"2".equals(user.getBranchType())) {
            ScoreSummaryFilter scoreSummaryFilter = new ScoreSummaryFilter();
            scoreSummaryFilter.setUserId(checkObjectId);
            List<ScoreSummary> scoreSummaries = scoreSummaryService.queryByFilterNoPage(scoreSummaryFilter);
            if (ObjectUtils.isNotBlank(scoreSummaries)) {
                ScoreSummary summary = scoreSummaries.get(0);
                resultMap1.put("finalScore", StringUtils.isBlank(summary.getScore()) ? "——" : NumberUtils.keepPrecision(summary.getScore(), 2) + "");   //最终得分
                resultMap1.put("finalRank", StringUtils.isBlank(summary.getRank()) ? "——" : summary.getRank());     //最终排名
                resultMap1.put("itemRank", StringUtils.isBlank(summary.getTypeRank()) ? "——" : summary.getTypeRank());  //组内排名
                resultMap1.put("name", StringUtils.isBlank(user.getName()) ? "——" : user.getName());          //名字
                resultMap1.put("branch", StringUtils.isBlank(user.getBranch()) ? "——" : user.getBranch());      //组别
                resultMap1.put("branchType", branchType);      //组别
            } else {
                resultMap1.put("finalScore", "任务尚未完成，故无最终得分 ");   //最终得分
                resultMap1.put("finalRank", "——");     //最终排名
                resultMap1.put("itemRank", "——");  //组内排名
                resultMap1.put("name", StringUtils.isBlank(user.getName()) ? "——" : user.getName());          //名字
                resultMap1.put("branch", StringUtils.isBlank(user.getBranch()) ? "——" : user.getBranch());
                resultMap1.put("branchType", branchType);      //组别
            }
            result.put("data1", resultMap1);
        }
        /**************************************得分统计**************************************/
        if (!"2".equals(user.getBranchType()) && !"4".equals(user.getBranchType())) {
            filter.setCheckObjectId(user.getSysId());
        }
        //督查组
        if ("4".equals(user.getBranchType())) {
            if (StringUtils.isNotBlank(jobGroupMap.get(user.getPhone()))) {
                filter.setCheckObjectId(jobGroupMap.get(user.getPhone()));
            }
        }
        List<Map<String, Object>> list = gradePointService.getScoreNumCount(filter);
        result.put("data2", list);
        /**************************************得分公式**************************************/
        StringBuffer sb = new StringBuffer();
        StringBuffer sbCount = new StringBuffer();
        for (int i = 0; i < list.size(); i++) {
            String soucre = (String) list.get(i).get("soucre");
            BigInteger countBigInteger = (BigInteger) list.get(i).get("count");
            String count = countBigInteger.intValue()+"";
            if (soucre.contains("-")) {
                sb.append("-" + soucre.replace("-", "") + "*" + count);
            } else {
                if (i > 0) {
                    sb.append("+(" + soucre + "*" + count + ")");
                } else {
                    sb.append("(" + soucre + "*" + count + ")");
                }
            }
            if (i > 0) {
                sbCount.append("+"+count);
            } else {
                sbCount.append(count);
            }
        }
        String formula = "(" + sb.toString() + ")/" + "(" + sbCount.toString() + ")" + " + (" + sb.toString() + ")/10 = " + resultMap1.get("finalScore");
        result.put("data3", formula);
        result.put("code", "200");
        result.put("message", "操作成功");
        result.put("userAuth", user);
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/queryTackToTaskGradePointList", method = RequestMethod.POST)
    public Map<String, Object> queryTackToTaskGradePointList(@RequestBody GradePointFilter filter) {
        List<GradePoint> lists = gradePointService.queryTackToTaskGradePointList(filter);
        return coverMessage("200", "获取成功", lists);
    }
}
